package ro.isdc.navigator.utils.hibernate.usertypes;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

/**
 * Converts a boolean to a SQL CHAR(1) and viceversa.
 * 
 * @author Andrei Chirila / ISDC! Romania
 * @version 1.0
 * @date Jul 2, 2009
 */
public class BooleanType implements UserType {

  public BooleanType() {

  }

  public int[] sqlTypes() {

    return new int[] { Types.CHAR };

  }

  public Class<Boolean> returnedClass() {

    return boolean.class;

  }

  public boolean equals(Object x, Object y) throws HibernateException {

    return (x == y) || (x != null && y != null && (x.equals(y)));

  }

  public Object nullSafeGet(ResultSet inResultSet, String[] names, Object o)

  throws HibernateException, SQLException {

    String val = (String) Hibernate.STRING.nullSafeGet(inResultSet, names[0]);

    if (val != null) {
      if (val.equalsIgnoreCase("1")) {
        return true;
      }
    }
    return false;

  }

  public void nullSafeSet(PreparedStatement inPreparedStatement, Object o, int i)

  throws HibernateException, SQLException {

    if (o == null) {
      inPreparedStatement.setNull(i, Types.CHAR);
    } else {
      String val = ((Boolean) o).booleanValue() ? "1" : "0";
      inPreparedStatement.setString(i, val);
    }
  }

  public Object deepCopy(final Object o) throws HibernateException {

    if (o == null) {
      return null;
    }

    return (Boolean) o;

  }

  public boolean isMutable() {

    return false;

  }

  public Serializable disassemble(Object value) {
    return (Serializable) value;
  }

  public Object assemble(Serializable cached, Object owner) {
    return cached;
  }

  public int hashCode(Object x) {
    return x.hashCode();
  }

  public Object replace(Object original, Object target, Object owner) {
    return original;
  }
}
